<template>
  <div>
    <Card dis-hover>
      <Form ref="queryForm">
        <Row style="margin-bottom: 10px;">
          <Col span="24" style="text-align: right;">
            <Button @click="create" icon="md-create" type="primary" v-if="type==='launch'" style="margin-right: 10px;"
                    :disabled="!hasPermission('Pages.FlowInstances.Launch')">
              启动新流程
            </Button>
            <Button icon="md-cloud-download"
                    style="margin-right:10px;"
                    type="info" @click="download" :disabled="!hasPermission('Pages.FlowInstances.Export')">导出到EXCEL
            </Button>
            <Button @click="getPage" icon="md-search" type="success">搜索</Button>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem prop="filter" style="width:100%;margin-bottom: 10px;">
              <Input v-model="pageRequest.filter" placeholder="在流程名称、流程描述、当前节点中搜索" clearable
                     @on-clear="handleClear"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem prop="date" style="width:100%;margin-bottom:10px;">
              <DatePicker placeholder="选择创建时间范围" split-panels style="width:100%;" type="daterange"
                          placement="bottom-start" :editable="false" @on-change="dateChange"
                          @on-clear="handleClear" transfer></DatePicker>
            </FormItem>
          </Col>
        </Row>

      </Form>
      <Table :loading="loading" :columns="columns" no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" border
             :data="list" class="margin-top-10" @on-sort-change="sortingChange">
        <template slot-scope="{row}" slot="state">
          <Tag v-if="row.state===0" color="primary">运行中</Tag>
          <Tag v-if="row.state===1" color="success">已完成</Tag>
          <Tag v-if="row.state===2" color="purple">被召回</Tag>
          <Tag v-if="row.state===3" color="error">被拒绝</Tag>
          <Tag v-if="row.state===4" color="warning">被驳回</Tag>
          <Tag v-if="row.state===5" color="green">草稿</Tag>
        </template>
        <template slot-scope="{row}" slot="actions">
          <Dropdown @on-click="handleClickActionDropdown" placement="bottom-end" transfer>
            <Button type="primary" size="small">
              操作
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">

              <DropdownItem :name="JSON.stringify({row:row,name:'verify'})"
                            :disabled="type!=='backlog' || !hasPermission('Pages.FlowInstances.Verify')">
                处理
              </DropdownItem>
              <DropdownItem :name="JSON.stringify({row:row,name:'recall'})"
                            :disabled="!(row.state===0 && type==='launch' && row.historyCount===0) || !hasPermission('Pages.FlowInstances.Recall')">
                召回
              </DropdownItem>
              <DropdownItem :name="JSON.stringify({row:row,name:'restart'})"
                            :disabled="!(type==='draft' ||  row.activityNodeType==='start') || !hasPermission('Pages.FlowInstances.Restart')">
                重启
              </DropdownItem>
              <DropdownItem :name="JSON.stringify({row:row,name:'detail'})" divided
                            :disabled="!hasPermission('Pages.FlowInstances.Display')">详情
              </DropdownItem>
              <DropdownItem :name="JSON.stringify({row:row,name:'remove'})" divided
                            :disabled="!( row.state===5 || $store.state.session.user.userName==='admin') || !hasPermission('Pages.FlowInstances.Delete')">
                删除
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>

        </template>
      </Table>
      <Page show-sizer show-total :total="totalCount" class="margin-top-10" @on-change="pageChange"
            @on-page-size-change="pageSizeChange" :page-size="pageSize" :current="currentPage"
            :page-size-opts="[10,20,30,40]">

      </Page>
    </Card>

  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import PageRequest from '@/store/entities/page-request';
import Util from '@/lib/util';
import CollapseTransition from '@/components/common/collapse-transition';
import Runtime from '@/views/flow/flow-instance/module/runtime';
import AllotModal from '@/views/flow/flow-instance/modal/allot-modal.vue';

class PageFlowInstanceRequest extends PageRequest {
  filter: string = '';
  sorting: string = '';
  startTime: string = '1900-01-01 00:00:00';
  endTime: string = '2099-12-31 23:59:59';
  type: string = '';
  state: number;
}

@Component({
  components: {
    CollapseTransition, AllotModal
  },
})
export default class FlowInstance extends AbpBase {
  name: string = 'FlowInstance';
  @Prop({type: String, default: ''}) type: string;


  advancedSearch: boolean = false;
  pageRequest: PageFlowInstanceRequest = new PageFlowInstanceRequest();
  columns = [
    {
      title: '当前状态',
      key: 'state',
      align: 'center',
      width: 110,
      slot: 'state',
    },
    {
      title: '流程名称',
      key: 'name',
      align: 'center',
      render: (h, params) => {
        return h('a', {
          attrs: {
            href: 'javascript:void(0);',
          },
          on: {
            click: () => {
              if (this.hasPermission('Pages.FlowInstances.Display')) {
                this.display(params.row);
              }
            },
          },
        }, params.row.name);
      },
      sortable: this.$config.sorting.flow.instance,
      minWidth: 300,
    },
    {
      title: '流程描述',
      key: 'description',
      align: 'center',
      minWidth: 300,
    },
    {
      title: '当前节点',
      key: 'activityNodeName',
      align: 'center',
      width: 120,
    },
    {
      title: '创建用户',
      key: 'creationFullName',
      align: 'center',
      width: 120,

    },
    {
      title: '创建时间',
      key: 'creationTime',
      align: 'center',
      width: 180,
      sortable: this.$config.sorting.flow.instance,
      render: (h: any, params: any) => {
        return h('span', {}, Util.getTime((params.row.creationTime)));
      },
    },
    {
      title: '操作',
      width: 110,
      slot: 'actions',
      align: 'center',
    },
  ];

  @Watch('$route')
  routeChange(to, from) {
  }

  @Watch('type')
  typeChange() {
    this.getPage();
  }

  get list() {
    return this.$store.state.flowInstance.list;
  }

  get loading() {
    return this.$store.state.flowInstance.loading;
  }

  get pageSize() {
    return this.$store.state.flowInstance.pageSize;
  }

  get totalCount() {
    return this.$store.state.flowInstance.totalCount;
  }

  get currentPage() {
    return this.$store.state.flowInstance.currentPage;
  }

  get excelFile() {
    return this.$store.state.book.excelFile;
  }


  dateChange(date: any[]) {
    this.pageRequest.startTime = (date[0] === '' ? '1900-01-01' : date[0]) + ' 00:00:00';
    this.pageRequest.endTime = (date[1] === '' ? '2099-12-31' : date[1]) + ' 23:59:59';

  }

  create() {
    Util.addOther(this, 'flow-instance-insert', {which: 'launch', id: 0});
  }

  toggleClick() {
    this.advancedSearch = !this.advancedSearch;
  }

  handleClear() {
    this.getPage();
  }

  async handleClickActionDropdown(name: string) {
    const temp: any = JSON.parse(name);
    switch (temp.name) {
      case 'verify':
        this.display(temp.row);
        break;
      case 'recall':
        this.recall(temp.row);
        break;
      case 'restart':
        await this.restart(temp.row);
        break;
      case 'detail':
        this.display(temp.row);
        break;
      case 'remove':
        await this.remove(temp.row);
        break;
    }
  }

  async restart(row: any) {
    Util.addOther(this, 'flow-instance-insert', {which: row.state, id: row.id});
  }

  async recall(row: any) {
    await this.$store.dispatch({
      type: 'flowInstance/recallFlowInstance',
      data: {
        id: row.id,
      }
    });
    this.$Message.success({
      background: true,
      content: '流程 ' + row.name + ' 已成功召回',
    });

    this.$router.push({name: 'draft'});

  }

  display(row: any) {
    Util.addOther(this, 'flow-instance-detail', {which: row.flag, id: row.id});
  }

  async pageChange(page: number) {
    this.$store.commit('flowInstance/setCurrentPage', page);
    await this.getPage();
  }

  async pageSizeChange(pageSize: number) {
    this.$store.commit('flowInstance/setPageSize', pageSize);
    await this.getPage();
  }

  async sortingChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.pageRequest.sorting = sorting.key + ' ' + sorting.order;
      }
      await this.getPage();
    }
  }

  async getPage() {
    this.pageRequest.maxResultCount = this.pageSize;
    this.pageRequest.skipCount = (this.currentPage - 1) * this.pageSize;
    this.pageRequest.type = this.type;
    await this.$store.dispatch({
      type: 'flowInstance/obtainFlowInstances',
      data: this.pageRequest,
    });
  }

  remove(row: any) {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要删除流程 ' + row.name + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'flowInstance/deleteFlowInstance',
          data: {
            id: row.id,
          },
        });
        this.$Message.success({
          background: true,
          content: '流程 ' + row.name + ' 已删除成功',
        });
        await this.getPage();
      },

      onCancel: () => {
      },
    });
  }

  async download() {
    await this.$store.dispatch({
      type: 'flowInstance/obtainFlowInstancesToExcel',
      data: this.pageRequest,
    });
    if (this.hasPermission('Pages.Files.Download')) {
      Util.downloadWithToken('/api/File/DownloadTempFile?fileType=' + this.excelFile.fileType + '&fileToken=' + this.excelFile.fileToken + '&fileName=' + this.excelFile.fileName, this.excelFile.fileName, this.excelFile.fileType);
    } else {
      this.$Message.error({
        background: true,
        content: '下载失败，缺少文件下载权限',
        duration: this.$config.duration,
      });
    }
  }

  async created() {
    await this.getPage();
  }
}
</script>

<style lang="less" scoped>

</style>
